﻿using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Helper;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Models.Entitys;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Models.ResponseModel;
using RndMaterialDisposalService.Services;
using RndMaterialDisposalService.Services.Interface;
using AutoMapper;
using Ganss.Excel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NPOI.POIFS.Crypt.Dsig;
using Razor.Templating.Core;
using System.Text.Json;

namespace RndMaterialDisposalService.Controllers.VehicleDispatch
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class InternalVehicleController : ControllerBase
    {

        private readonly string ProcessFullName = "VehicleDispatch\\InternalVehicle";
        private readonly string SaveFormDataUrl = "/api/WorkflowData/ApplicationData";
        private readonly string ProcessFolioUrl = "/api/WorkflowData/ApplicationNumber";

        private readonly IMapper mapper;
        private readonly IConfiguration configuration;
        private readonly IInternalVehicleService internalVehicleService;
        private readonly ILogger<InternalVehicleController> logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_logger"></param>
        /// <param name="_mapper"></param>
        /// <param name="_configuration"></param>
        /// <param name="_vehicleMaintenanceService"></param>
        public InternalVehicleController(ILogger<InternalVehicleController> _logger,
            IConfiguration _configuration,
            IMapper _mapper,
            IInternalVehicleService _vehicleMaintenanceService)
        {
            logger = _logger;
            mapper = _mapper;
            configuration = _configuration;
            internalVehicleService = _vehicleMaintenanceService;
        }

        /// <summary>
        /// 获取表单数据
        /// </summary>
        /// <param name="procInstID"></param>
        /// <returns></returns>
        [HttpGet("GetFormData")]
        public async Task<IActionResult> GetFormData(string? procInstID)
        {
            var CommonServiceHost = configuration.GetSection("CommonServiceHost").Value;
            var result = new FormInfoResp();
            if (!string.IsNullOrEmpty(procInstID))
            {
                var url = $"{CommonServiceHost}{SaveFormDataUrl}?procInstID={procInstID}";
                result = await HttpHelper.GetAsync<FormInfoResp>(url);
                result.ViewsStatus = "Approval";
                return Ok(result);
            }

            var formDataModel = new InternalVehicleFormDataReq();
            var url2 = $"{CommonServiceHost}{ProcessFolioUrl}?workflowCode={ProcessFullName}";
            var appNumber = await HttpHelper.GetAsync<string>(url2);
            result.ApplicationNumber = appNumber;
            result.ViewsStatus = "Start";
            result.FormData = JsonSerializer.Serialize(formDataModel, new JsonSerializerOptions()
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            });
            return Ok(result);
        }

        /// <summary>
        /// 保存报表数据
        /// </summary>
        /// <param name="formData"></param>
        /// <param name="mapper"></param>
        /// <returns></returns>
        [HttpPost("SaveReportData")]
        public async Task<IActionResult> SaveReportData(InternalVehicleFormDataReq formData)
        {
            try
            {
                var model = mapper.Map<InternalVehicleReportDto>(formData);
                var result = await internalVehicleService.SaveReportData(model);
                logger.LogInformation($"新增报表数据（内部人员用车申请表）,流程主题：{formData.FormHeader.Subject},数量：{result},时间：{DateTime.Now}");
                return Ok(result);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"新增报表数据（内部人员用车申请表）,流程主题：{formData.FormHeader.Subject},异常原因：{ex.ToString()},时间：{DateTime.Now}");
                throw;
            }
        }

        /// <summary>
        /// 获取报表数据
        /// </summary>
        /// <param name="inputCondition"></param>
        /// <returns></returns>
        [HttpPost("GetVehicleReportData")]
        [PageList]
        public async Task<IActionResult> VehicleMaintenanceReportData(InternalVehicleReportDataReq inputCondition)
        {
            var data = await internalVehicleService.GetReportData(inputCondition);
            var result = ApiResponsePageList<InternalVehicleReportDto>.CreatePageListByResult(data.list, inputCondition.PageIndex, inputCondition.PageSize, data.count);
            return Ok(result);
        }

        /// <summary>
        /// 导出报表文件
        /// </summary>
        /// <param name="inputCondition"></param>
        /// <returns></returns>
        [HttpPost("VehicleReportExport")]
        [PageList]
        public async Task<IActionResult> VehicleMaintenanceReportExport(InternalVehicleReportDataReq inputCondition)
        {
            inputCondition.PageIndex = 1;
            inputCondition.PageSize = 65535;
            var data = await internalVehicleService.GetReportData(inputCondition);
            var list = mapper.Map<List<InternalVehicleReportExportModel>>(data.list);
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            if (!System.IO.Directory.Exists($"{fileDir}\\Report"))
            {
                Directory.CreateDirectory($"{fileDir}\\Report");
            }
            var filePath = $"Report\\内部人员用车申请表{Guid.NewGuid().ToString("N")}.xlsx";
            await new ExcelMapper().SaveAsync($"{fileDir}\\{filePath}", list);
            return Ok(filePath);
        }

        /// <summary>
        /// 获取费用单报表
        /// </summary>
        /// <param name="formId"></param>
        /// <returns></returns>
        [HttpGet("ConfirmationExpenseData")]
        public async Task<IActionResult> GetConfirmationExpenseFormData(string formId)
        {
            var result = await internalVehicleService.GetConfirmationExpenseFormData(formId);
            return Ok(result);
        }

        /// <summary>
        /// 保存费用单报表
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("SaveConfirmationExpenseData")]
        public async Task<IActionResult> SaveConfirmationExpenseFormData(ConfirmationExpenseDto formData)
        {
            var result = await internalVehicleService.SaveConfirmationExpenseFormData(formData);
            return Ok(result);
        }

        /// <summary>
        /// 费用单报表
        /// </summary>
        /// <param name="inputCondition"></param>
        /// <returns></returns>
        [HttpPost("ConfirmationExpenseReportData")]
        [PageList]
        public async Task<IActionResult> ConfirmationExpenseReportData(ConfirmationExpenseReportDataReq inputCondition)
        {
            var data = await internalVehicleService.ConfirmationExpenseReportData(inputCondition);
            var result = ApiResponsePageList<ConfirmationExpenseDto>.CreatePageListByResult(data.list, inputCondition.PageIndex, inputCondition.PageSize, data.count);
            return Ok(result);
        }

        /// <summary>
        /// 导出费用单报表
        /// </summary>
        /// <param name="inputCondition"></param>
        /// <returns></returns>
        [HttpPost("ConfirmationExpenseReportExport")]
        public async Task<IActionResult> ConfirmationExpenseReportExport(ConfirmationExpenseReportDataReq inputCondition)
        {
            inputCondition.PageIndex = 1;
            inputCondition.PageSize = 65535;
            var data = await internalVehicleService.ConfirmationExpenseReportData(inputCondition);
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            if (!System.IO.Directory.Exists($"{fileDir}\\Report"))
            {
                Directory.CreateDirectory($"{fileDir}\\Report");
            }
            var filePath = $"Report\\车辆预定及费用确认单{Guid.NewGuid().ToString("N")}.xlsx";
            await new ExcelMapper().SaveAsync($"{fileDir}\\{filePath}", data.list);
            return Ok(filePath);
        }
    }
}
